using AutoMapper;
using B.S.RbacData.ErrorCode;
using B.S.RbacData.Infrastructure;
using ContentmanagementBase.Domain;
using ContentmanagementBaseWrite.API.Applications.Commands.Drugstores;
using MediatR;

namespace ContentmanagementBaseWrite.API.Applications.Commandhandlters.Drugstores
{
    /// <summary>
    /// 批量删除药店命令处理器
    /// </summary>
    public class BatchDeleteDrugstoreCommandHandler : IRequestHandler<BatchDeleteDrugstoreCommand, ApiResult<int>>
    {
        /// <summary>
        /// 药店仓储
        /// </summary>
        private readonly IBaseRepository<PharmacyManagementModel> _drugstoreRepository;
        /// <summary>
        /// 映射器
        /// </summary>
        private readonly IMapper _mapper;
        /// <summary>
        /// 日志记录器
        /// </summary>
        private readonly ILogger<BatchDeleteDrugstoreCommandHandler> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="drugstoreRepository">药店仓储</param>
        /// <param name="mapper">映射器</param>
        /// <param name="logger">日志记录器</param>
        public BatchDeleteDrugstoreCommandHandler(IBaseRepository<PharmacyManagementModel> drugstoreRepository, IMapper mapper, ILogger<BatchDeleteDrugstoreCommandHandler> logger)
        {
            _drugstoreRepository = drugstoreRepository;
            _mapper = mapper;
            _logger = logger;
        }

        /// <summary>
        /// 处理批量删除药店命令
        /// </summary>
        /// <param name="request">请求</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns></returns>
        public async Task<ApiResult<int>> Handle(BatchDeleteDrugstoreCommand request, CancellationToken cancellationToken)
        {
            try
            {
                _logger.LogInformation("开始处理药店批量删除命令，药店ID列表：{DrugstoreIds}", string.Join(",", request.DrugstoreIds));

                // 验证输入参数
                if (request.DrugstoreIds == null || !request.DrugstoreIds.Any())
                {
                    _logger.LogWarning("药店ID列表为空");
                    return new ApiResult<int>
                    {
                        code = ResultEnumCode.error,
                        message = "请选择要删除的药店！",
                        data = 0
                    };
                }

                // 去重处理
                var distinctIds = request.DrugstoreIds.Distinct().ToList();
                _logger.LogDebug("去重后的药店ID列表：{DistinctIds}", string.Join(",", distinctIds));

                // 获取所有要删除的药店信息
                var drugstoresToDelete = _drugstoreRepository.GetAll()
                    .Where(x => distinctIds.Contains(x.Id) && !x.IsDeleted)
                    .ToList();

                if (!drugstoresToDelete.Any())
                {
                    _logger.LogWarning("未找到可删除的药店");
                    return new ApiResult<int>
                    {
                        code = ResultEnumCode.error,
                        message = "未找到可删除的药店！",
                        data = 0
                    };
                }

                _logger.LogInformation("找到 {Count} 个可删除的药店", drugstoresToDelete.Count);

                // 检查是否有推荐的药店需要特殊处理（可选的业务逻辑）
                var recommendedDrugstores = drugstoresToDelete.Where(x => x.IsRecommend).ToList();
                if (recommendedDrugstores.Any())
                {
                    var recommendedNames = string.Join("、", recommendedDrugstores.Select(x => x.PharmacyName));
                    _logger.LogWarning("存在推荐药店将被删除：{RecommendedNames}", recommendedNames);
                    // 这里可以根据业务需求决定是否允许删除推荐药店
                    // 如果不允许，可以返回错误信息
                }

                _logger.LogDebug("所有药店检查通过，开始执行软删除操作");

                // 执行软删除操作
                var deletedCount = 0;
                var failedDrugstores = new List<string>();

                foreach (var drugstore in drugstoresToDelete)
                {
                    try
                    {
                        drugstore.IsDeleted = true;
                        drugstore.UpdatedTime = DateTime.Now;
                        drugstore.UpdatedBy = 1; // 这里应该从当前用户上下文获取

                        var result = await _drugstoreRepository.UpdateAsync(drugstore);
                        if (result > 0)
                        {
                            deletedCount++;
                            _logger.LogDebug("药店 {PharmacyName}(ID:{Id}) 删除成功", drugstore.PharmacyName, drugstore.Id);
                        }
                        else
                        {
                            failedDrugstores.Add($"{drugstore.PharmacyName}(ID:{drugstore.Id})");
                            _logger.LogWarning("药店 {PharmacyName}(ID:{Id}) 删除失败", drugstore.PharmacyName, drugstore.Id);
                        }
                    }
                    catch (Exception ex)
                    {
                        failedDrugstores.Add($"{drugstore.PharmacyName}(ID:{drugstore.Id})");
                        _logger.LogError(ex, "删除药店 {PharmacyName}(ID:{Id}) 时发生异常", drugstore.PharmacyName, drugstore.Id);
                    }
                }

                _logger.LogInformation("批量删除操作完成，成功删除 {DeletedCount} 个药店，失败 {FailedCount} 个", 
                    deletedCount, failedDrugstores.Count);

                // 根据删除结果返回相应的响应
                if (deletedCount == drugstoresToDelete.Count)
                {
                    return new ApiResult<int>
                    {
                        code = ResultEnumCode.Ok,
                        message = $"成功删除 {deletedCount} 个药店",
                        data = deletedCount
                    };
                }
                else if (deletedCount > 0)
                {
                    var failedMessage = failedDrugstores.Any() ? $"，失败的药店：{string.Join("、", failedDrugstores)}" : "";
                    return new ApiResult<int>
                    {
                        code = ResultEnumCode.Ok,
                        message = $"部分删除成功，成功删除 {deletedCount} 个药店，共 {drugstoresToDelete.Count} 个{failedMessage}",
                        data = deletedCount
                    };
                }
                else
                {
                    var failedMessage = failedDrugstores.Any() ? $"失败的药店：{string.Join("、", failedDrugstores)}" : "未知原因";
                    return new ApiResult<int>
                    {
                        code = ResultEnumCode.fails,
                        message = $"药店删除失败，{failedMessage}",
                        data = 0
                    };
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "药店批量删除过程中发生异常，药店ID列表：{DrugstoreIds}", string.Join(",", request.DrugstoreIds));
                return new ApiResult<int>
                {
                    code = ResultEnumCode.fails,
                    message = $"药店批量删除异常：{ex.Message}",
                    data = 0
                };
            }
        }
    }
}